<template>
  <div class="permission-mol">
    <div class="tit">当前角色：<span>{{ roleName }}</span></div>
    <!--<div class="plat-box">-->
      <!--<div class="hd">-->
        <!--<el-checkbox v-model="platHeadChecked" @change="platHandleCheckedChange">杏花鸡产业大数据中心</el-checkbox>-->
      <!--</div>-->
      <!--<div class="bd">-->
        <!--<el-tree-->
          <!--:data="platList"-->
          <!--show-checkbox-->
          <!--node-key="value"-->
          <!--ref="platTree"-->
          <!--:default-expanded-keys="platExpandedKeys"-->
          <!--:props="defaultProps"-->
          <!--@check="platTreeCheckedChange">-->
        <!--</el-tree>-->
      <!--</div>-->
    <!--</div>-->
    <br>
    <div class="xhcApp-backEnd">
      <!--<div class="admin-box">-->
        <!--<div class="hd">-->
          <!--<el-checkbox v-model="APPHeadChecked" @change="APPHandleCheckedChange">杏花鸡APP</el-checkbox>-->
        <!--</div>-->
        <!--<div class="bd">-->
          <!--<el-tree-->
            <!--:data="APPList"-->
            <!--show-checkbox-->
            <!--node-key="value"-->
            <!--ref="APPTree"-->
            <!--:default-expanded-keys="APPExpandedKeys"-->
            <!--:props="defaultProps"-->
            <!--@check="APPTreeCheckedChange">-->
          <!--</el-tree>-->
        <!--</div>-->
      <!--</div>-->
      <div class="admin-box">
        <div class="hd">
          <el-checkbox v-model="adminHeadChecked" @change="adminHandleCheckedChange">麻鸡后台管理系统</el-checkbox>
        </div>
        <div class="bd">
          <el-tree
            :data="adminList"
            show-checkbox
            node-key="value"
            ref="adminTree"
            :default-expanded-keys="adminExpandedKeys"
            :props="defaultProps"
            @check="treeCheckedChange">
          </el-tree>
        </div>
      </div>
    </div>
    <div class="error-info" v-if="error">请至少选择一个权限</div>
    <div class="addbtn">
      <el-button type="primary" @click="saveFrom">保存</el-button>
    </div>
  </div>
</template>

<script>
import { setSession, getSession } from '@/utils/index'
import { setMeunPermission } from '@/utils/menuPermission'
export default {
  name: 'permission',
  data () {
    return {
      error: false,
      roleName: this.$route.query.roleName, //角色名称
      orgId: null,//角色id
      menuList: [],
      platList: [], // 大数据中心菜单列表
      APPList: [], // APP菜单列表
      adminList: [],// 后台管理系统菜单列表
      APPExpandedKeys: [], // APP——默认展开
      adminExpandedKeys: [], // 后台管理系统——默认展开
      platHeadChecked: false, // 大数据中心——头部选择框
      platId: [], // 大数据中心——平台id
      APPId: [], // APP——id
      platDataChecked: [],
      APPHeadChecked: false, // APP——头部选择框
      adminHeadChecked: false, // 后台管理系统——头部选择框
      adminId: [], // 后台管理系统——平台id
      APPDataChecked: [],
      adminDataChecked: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuStatics: [],// 静态菜单集合
      menuCustom: [],// 动态菜单集合
      isSuperAdmin: this.$store.state.user.isSuperAdmin === 'true', // 是否是超级管理员
      platExpandedKeys: [], // 大数据中心——默认展开
    };
  },
  watch:{
    'platDataChecked'(val){
      // this.platHeadChecked=val.length===this.platList.length ? true : false
      let length = 0
      this.platList.map((el1) => {
        length++;
        el1.children.length && el1.children.map(el2 => {
          length++;
          el2.children.length && el2.children.map(el3 => {
            length++;
            el3.children.length && el3.children.map(el4 => {
              length++;
            })
          })
        })
      });
      this.platHeadChecked = val.length === length ? true : false
    },
    'APPDataChecked'(val){
      let length = 0
      this.APPList.map((el1) => {
        length++;
        el1.children.length && el1.children.map(el2 => {
          length++;
          el2.children.length && el2.children.map(el3 => {
            length++;
            el3.children.length && el3.children.map(el4 => {
              length++;
            })
          })
        })
      });
      this.APPHeadChecked = val.length === length ? true : false
    },
    'adminDataChecked'(val){
      let length = 0
      this.adminList.map((el1) => {
        length++;
        el1.children.length && el1.children.map(el2 => {
          length++;
          el2.children.length && el2.children.map(el3 => {
            length++;
            el3.children.length && el3.children.map(el4 => {
              length++;
            })
          })
        })
      });
      this.adminHeadChecked = val.length === length ? true : false
    },
  },
  created () {
    this.orgId = this.$route.query.orgId;
    // 获取数据
    this.getRolePermission()
  },
  methods: {
    /**
     * 获取全部菜单权限数据
     **/
    getRolePermission(){
      this.$api.role.getAllMenu({
        orgId: this.orgId,
        projectId: this.$store.state.user.projectId,
        isSuperAdmin: this.isSuperAdmin
      }).then(res => {
        const data = res.data || [];
        this.adminDataChecked = [];

        // const headItem = data.find(el => el.menuUrl === 'head');
        // this.platId = headItem.id; // 获取大数据中心id
        // this.platList = headItem.children || []; // 获取大数据中心菜单列表
        // this.initPlatPermissionData(); // 处理大数据中心菜单列表数据结构
        //
        // const APPItem = data.find(el => el.menuUrl === 'app');
        // this.APPId = APPItem.id; // 获取APP平台id
        // this.APPList = APPItem.children || []; // 获取APP菜单列表
        // this.initAPPPermissionData(); // 处理APP菜单列表数据结构

        const backendItem = data.find(el => el.menuUrl === 'backend');
        this.adminId = backendItem.id; // 获取后台平台id
        this.adminList = backendItem.children || []; // 获取后台菜单列表
        this.initAdminPermissionData(); // 处理后台菜单列表数据结构
      });
    },
    /**
     * 处理大数据中心菜单列表数据结构
     **/
    initPlatPermissionData () {
      let length = 0;
      this.platList.map((el1) => {
        el1.parentIds = el1.parentId
        el1.value = `${el1.menuType}/${el1.id}/${el1.parentId}/${el1.parentIds}`
        // 初始化默认勾选节点
        if(!el1.children.length) {
          if (el1.checked) this.platDataChecked.push(el1.value);
          length++;
        }
        // 设置默认展开节点
        this.platExpandedKeys.push(el1.value);
        el1.children.length && el1.children.map(el2 => {
          el2.parentIds = `${el1.parentId},${el2.parentId}`
          el2.value = `${el2.menuType}/${el2.id}/${el2.parentId}/${el2.parentIds}`
          // 初始化默认勾选节点
          if(!el2.children.length) {
            if (el2.checked) this.platDataChecked.push(el2.value);
            length++;
          }
          el2.children.length && el2.children.map(el3 => {
            el3.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId}`
            el3.value = el3.children.length ? el3.id : el3.value
            el3.value = `${el3.menuType}/${el3.value}/${el3.parentId}/${el3.parentIds}/${el2.menuType}`
            // 初始化默认勾选节点
            if(!el3.children.length) {
              if (el3.checked) this.platDataChecked.push(el3.value);
              length++;
            }
            // 只有超管才能编辑菜单设置
            if (el1.menuUrl === 'settingsManagement' && !this.isSuperAdmin) {
              el1.disabled = true
              el2.disabled = true
              el3.disabled = true
            }
            el3.children.length && el3.children.map(el4 => { // 最后一级
              el4.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId},${el4.parentId}`
              el4.value = `${el4.menuType}/${el4.value}/${el4.parentId}/${el4.parentIds}/${el3.menuType}`
              length++;
              if(el4.checked) {
                this.platDataChecked.push(el4.value);
              }
            })
          })
        })
      });
      setTimeout(() => {
        this.$refs.platTree.setCheckedKeys(this.platDataChecked);
        if (length === this.platDataChecked.length && this.platDataChecked.length!==0) this.platHeadChecked = true;
      }, 200);
    },
    /**
     * 处理APP菜单列表数据结构
     **/
    initAPPPermissionData () {
      let length = 0;
      this.APPList.map((el1) => {
        el1.parentIds = el1.parentId
        el1.value = `${el1.menuType}/${el1.id}/${el1.parentId}/${el1.parentIds}`
        // 初始化默认勾选节点
        if(!el1.children.length) {
          if (el1.checked) this.APPDataChecked.push(el1.value);
          length++;
        }
        // 设置默认展开节点
        this.APPExpandedKeys.push(el1.value);
        el1.children.length && el1.children.map(el2 => {
          el2.parentIds = `${el1.parentId},${el2.parentId}`
          el2.value = `${el2.menuType}/${el2.id}/${el2.parentId}/${el2.parentIds}`
          // 初始化默认勾选节点
          if(!el2.children.length) {
            if (el2.checked) this.APPDataChecked.push(el2.value);
            length++;
          }
          el2.children.length && el2.children.map(el3 => {
            el3.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId}`
            el3.value = el3.children.length ? el3.id : el3.value
            el3.value = `${el3.menuType}/${el3.value}/${el3.parentId}/${el3.parentIds}/${el2.menuType}`
            // 初始化默认勾选节点
            if(!el3.children.length) {
              if (el3.checked) this.APPDataChecked.push(el3.value);
              length++;
            }
            // 只有超管才能编辑菜单设置
            if (el1.menuUrl === 'settingsManagement' && !this.isSuperAdmin) {
              el1.disabled = true
              el2.disabled = true
              el3.disabled = true
            }
            el3.children.length && el3.children.map(el4 => { // 最后一级
              el4.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId},${el4.parentId}`
              el4.value = `${el4.menuType}/${el4.value}/${el4.parentId}/${el4.parentIds}/${el3.menuType}`
              length++;
              if(el4.checked) {
                this.APPDataChecked.push(el4.value);
              }
            })
          })
        })
      });
      setTimeout(() => {
        this.$refs.APPTree.setCheckedKeys(this.APPDataChecked);
        if (length === this.APPDataChecked.length && this.APPDataChecked.length!==0) this.APPHeadChecked = true;
      }, 200);
    },
    /**
     * 处理后台管理系统菜单列表数据结构
     **/
    initAdminPermissionData () {
      let length = 0;
      this.adminList.map((el1) => {
        el1.parentIds = el1.parentId
        el1.value = `${el1.menuType}/${el1.id}/${el1.parentId}/${el1.parentIds}`
        // 初始化默认勾选节点
        if(!el1.children.length) {
          if (el1.checked) this.adminDataChecked.push(el1.value);
          length++;
        }
        // 设置默认展开节点
        this.adminExpandedKeys.push(el1.value);
        el1.children.length && el1.children.map(el2 => {
          el2.parentIds = `${el1.parentId},${el2.parentId}`
          el2.value = `${el2.menuType}/${el2.id}/${el2.parentId}/${el2.parentIds}`
          // 初始化默认勾选节点
          if(!el2.children.length) {
            if (el2.checked) this.adminDataChecked.push(el2.value);
            length++;
          }
          el2.children.length && el2.children.map(el3 => {
            el3.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId}`
            el3.value = el3.children.length ? el3.id : el3.value
            el3.value = `${el3.menuType}/${el3.value}/${el3.parentId}/${el3.parentIds}/${el2.menuType}`
            // 初始化默认勾选节点
            if(!el3.children.length) {
              if (el3.checked) this.adminDataChecked.push(el3.value);
              length++;
            }
            // 只有超管才能编辑菜单设置
            if (el1.menuUrl === 'settingsManagement' && !this.isSuperAdmin) {
              el1.disabled = true
              el2.disabled = true
              el3.disabled = true
            }
            el3.children.length && el3.children.map(el4 => { // 最后一级
              el4.parentIds = `${el1.parentId},${el2.parentId},${el3.parentId},${el4.parentId}`
              el4.value = `${el4.menuType}/${el4.value}/${el4.parentId}/${el4.parentIds}/${el3.menuType}`
              length++;
              if(el4.checked) {
                this.adminDataChecked.push(el4.value);
              }
            })
          })
        })
      });
      setTimeout(() => {
        this.$refs.adminTree.setCheckedKeys(this.adminDataChecked);
        if (length === this.adminDataChecked.length && this.adminDataChecked.length!==0) this.adminHeadChecked = true;
      }, 200);
    },
    /**
    * 大数据中心--头部选择
    **/
    platHandleCheckedChange(val){
      // if(val){
      //   this.platDataChecked=[]
      //   this.platList.forEach((el) => {
      //     this.platDataChecked.push(el.id)
      //   })
      // }else{
      //   this.platDataChecked=[]
      // }
      // this.handleCheckedChange()
      if(val){
        this.platDataChecked=[]
        this.platList.map((el1) => {
          this.platDataChecked.push(el1.value)
          el1.children.length && el1.children.map(el2 => {
            this.platDataChecked.push(el2.value)
            el2.children.length && el2.children.map(el3 => {
              this.platDataChecked.push(el3.value)
              el3.children.length && el3.children.map(el4 => {
                this.platDataChecked.push(el4.value)
              })
            })
          })
        });
      }else{
        this.platDataChecked=[];
      }
      this.$refs.platTree.setCheckedKeys(this.platDataChecked);
      this.handleCheckedChange()
    },
    /**
    * APP--头部选择
    **/
    APPHandleCheckedChange(val){
      if(val){
        this.APPDataChecked=[]
        this.APPList.map((el1) => {
          this.APPDataChecked.push(el1.value)
          el1.children.length && el1.children.map(el2 => {
            this.APPDataChecked.push(el2.value)
            el2.children.length && el2.children.map(el3 => {
              this.APPDataChecked.push(el3.value)
              el3.children.length && el3.children.map(el4 => {
                this.APPDataChecked.push(el4.value)
              })
            })
          })
        });
      }else{
        this.APPDataChecked=[];
      }
      this.$refs.APPTree.setCheckedKeys(this.APPDataChecked);
      this.handleCheckedChange()
    },
    /**
     * 后台管理--头部选择
     **/
    adminHandleCheckedChange(val){
      if(val){
        this.adminDataChecked=[]
        this.adminList.map((el1) => {
          this.adminDataChecked.push(el1.value)
          el1.children.length && el1.children.map(el2 => {
            this.adminDataChecked.push(el2.value)
            el2.children.length && el2.children.map(el3 => {
              this.adminDataChecked.push(el3.value)
              el3.children.length && el3.children.map(el4 => {
                this.adminDataChecked.push(el4.value)
              })
            })
          })
        });
      }else{
        this.adminDataChecked=[];
      }
      this.$refs.adminTree.setCheckedKeys(this.adminDataChecked);
      this.handleCheckedChange()
    },
    /**
     * 大数据中心--树形选择框选择
     **/
    platTreeCheckedChange(){
      let treeChecked = this.$refs.platTree.getCheckedKeys() || [];
      this.platDataChecked = treeChecked
      this.handleCheckedChange()
    },
    /**
     * APP--树形选择框选择
     **/
    APPTreeCheckedChange(){
      let treeChecked = this.$refs.APPTree.getCheckedKeys() || [];
      this.APPDataChecked = treeChecked
      this.handleCheckedChange()
    },
    /**
     * 后台管理--树形选择框选择
     **/
    treeCheckedChange(){
      let treeChecked = this.$refs.adminTree.getCheckedKeys() || [];
      this.adminDataChecked = treeChecked
      this.handleCheckedChange()
    },
    handleCheckedChange() {
      this.error=false
      this.menuStatics=[]
      this.menuCustom=[]
      // 大数据中心
      if(this.platDataChecked.length) {
        this.menuStatics.push({
          id: this.platId,// 大数据中心最高层级id
          rights: []
        })
        this.platDataChecked.forEach((el) => {
          let arr = el.split('/');
          const menuType = arr[0];
          const id = arr[1];
          const parentId = arr[2];
          let parentIds = arr[3];
          const parentMenuType= arr.length > 4 ? arr[4] : null;
          if(menuType !== '4') { // 菜单
            const obj = {
              id: Number(id),
              rights: []
            }
            menuType==='0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
          } else { // 功能
            let item = parentMenuType === '0' ? this.menuCustom.find(o => o.id === Number(parentId)) : this.menuStatics.find(o => o.id === Number(parentId));
            if (item) {
              if(!item.rights.includes(id)) {
                item.rights.push(id)
              }
            } else {
              let rights = [id]
              const obj = {
                id: Number(parentId),
                rights
              }
              parentMenuType === '0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
            }
          }
          if (parentIds) {
            parentIds = parentIds.split(',')
            parentIds.map( oo => {
              const item1 = this.menuStatics.find(o => o.id === Number(oo));
              const item2 = this.menuCustom.find(o => o.id === Number(oo));
              if (!item1 && !item2) {
                this.menuStatics.push({
                  id: Number(oo),
                  rights: []
                })
              }
            })
          }
        })
        // this.platDataChecked.forEach((el) => {
        //   const obj = {
        //     id: Number(el),
        //     rights: []
        //   }
        //   this.menuStatics.push(obj)
        // })
      }
      // APP
      if(this.APPDataChecked.length) {
        this.menuStatics.push({
          id: this.APPId, // 后台管理系统最高层级id
          rights: []
        })
        this.APPDataChecked.forEach((el) => {
          let arr = el.split('/');
          const menuType = arr[0];
          const id = arr[1];
          const parentId = arr[2];
          let parentIds = arr[3];
          const parentMenuType= arr.length > 4 ? arr[4] : null;
          if(menuType !== '4') { // 菜单
            const obj = {
              id: Number(id),
              rights: []
            }
            menuType==='0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
          } else { // 功能
            let item = parentMenuType === '0' ? this.menuCustom.find(o => o.id === Number(parentId)) : this.menuStatics.find(o => o.id === Number(parentId));
            if (item) {
              if(!item.rights.includes(id)) {
                item.rights.push(id)
              }
            } else {
              let rights = [id]
              const obj = {
                id: Number(parentId),
                rights
              }
              parentMenuType === '0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
            }
          }
          if (parentIds) {
            parentIds = parentIds.split(',')
            parentIds.map( oo => {
              const item1 = this.menuStatics.find(o => o.id === Number(oo));
              const item2 = this.menuCustom.find(o => o.id === Number(oo));
              if (!item1 && !item2) {
                this.menuStatics.push({
                  id: Number(oo),
                  rights: []
                })
              }
            })
          }
        })
      }
      // 后台管理系统
      if(this.adminDataChecked.length) {
        this.menuStatics.push({
          id: this.adminId, // 后台管理系统最高层级id
          rights: []
        })
        this.adminDataChecked.forEach((el) => {
          let arr = el.split('/');
          const menuType = arr[0];
          const id = arr[1];
          const parentId = arr[2];
          let parentIds = arr[3];
          const parentMenuType= arr.length > 4 ? arr[4] : null;
          if(menuType !== '4') { // 菜单
            const obj = {
              id: Number(id),
              rights: []
            }
            menuType==='0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
          } else { // 功能
            let item = parentMenuType === '0' ? this.menuCustom.find(o => o.id === Number(parentId)) : this.menuStatics.find(o => o.id === Number(parentId));
            if (item) {
              if(!item.rights.includes(id)) {
                item.rights.push(id)
              }
            } else {
              let rights = [id]
              const obj = {
                id: Number(parentId),
                rights
              }
              parentMenuType === '0' ? this.menuCustom.push(obj) : this.menuStatics.push(obj)
            }
          }
          if (parentIds) {
            parentIds = parentIds.split(',')
            parentIds.map( oo => {
              const item1 = this.menuStatics.find(o => o.id === Number(oo));
              const item2 = this.menuCustom.find(o => o.id === Number(oo));
              if (!item1 && !item2) {
                this.menuStatics.push({
                  id: Number(oo),
                  rights: []
                })
              }
            })
          }
        })
      }
    },
    /**
     * 保存
     **/
    saveFrom() {
      this.handleCheckedChange()
      if(!this.menuStatics.length && !this.menuCustom.length){
        this.error = true
        return
      }
      this.menuStatics.map(o => {
        o.rights = (o && o.rights) ? o.rights.join(',') : ''
      })
      this.menuCustom.map(o => {
        o.rights = (o && o.rights) ? o.rights.join(',') : ''
      })
      this.$api.role.saveAllMenu({
        roleId: this.orgId,
        projectId: this.$store.state.user.projectId,
        menu: this.menuStatics,
        menuCustom: this.menuCustom,
        // modifyUser: getSession('userId')
      }).then(() => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        setTimeout(() => {
          this.$router.push({ path: 'index' })
          setMeunPermission(getSession('Authorization')); // 重置菜单权限
        },1000)
      });
    },
  }
};
</script>
